<?php

/**
 * Class FileFilter
 */
class FileFilter
{

    /**
     * @var string
     */
    protected $chinaRoutesUrl = 'https://raw.githubusercontent.com/ym/chnroutes2/master/chnroutes.txt';

    /**
     * @var array
     */
    public $chinaRoutes = [];

    public function __construct()
    {
        $this->chinaRoutes = $this->getChinaRoutes();
    }

    /**
     * ipInNetwork
     * @param $ip
     * @param $network
     * @return bool
     */
    public function ipInNetwork($ip, $network)
    {
        $ip = (double) (sprintf("%u", ip2long($ip)));

        $s = explode('/', $network);

        $networkStart = (double) (sprintf("%u", ip2long($s[0])));

        $networkEnd = $networkStart + pow(2, 32 - $s[1]) - 1;

        if ($ip >= $networkStart && $ip <= $networkEnd){
            return true;
        }
        return false;
    }

    /**
     * getChinaRoutes
     * @return array
     */
    protected function getChinaRoutes()
    {
        $file  = CACHE_PATH.DIRECTORY_SEPARATOR.'chnroutes.txt';
        if(!is_file($file) || (time() - filectime($file) >86400) ){
            $result = file_get_contents($this->chinaRoutesUrl);
            if(!empty($result)){
                file_put_contents($file,$result);
            }
        }
        $content = file_get_contents($file);
        $routes = explode("\n",$content);
        unset($routes[0],$routes[1]);
        return $routes;
    }

    /**
     * isChinaIp
     * @param $ip
     * @return bool
     */
    public function isChinaIp($ip)
    {

        if(empty($this->chinaRoutes)){
            return true;
        }

        foreach ($this->chinaRoutes as $network){
            if(empty($network))
                continue;
            if($this->ipInNetwork($ip, $network)){
                return true;
            }
        }
        return false;
    }
}